var ThreadState = {
    RUNNING: 0,
    WAITING: 1,
    DONE: 2,
    READY: 3
};

var MultithreadedScheduler = function() {
    this.threadPool = [];
    this.nextThreadId = 0;
    
    this.addThread = function(thread) {
        this.threadPool[this.nextThreadId] = thread;
        thread.pid = this.nextThreadId++;
        
        return thread.pid;
    };
    
    this.startThread = function(pid) {
        this.runThread(pid);
    };
    
    this.killThread = function(pid) {
        var currentThread = this.threadPool[pid];
        if (currentThread != null) {
            currentThread.state = ThreadState.DONE;
            
            if (currentThread.quantum) {
                clearTimeout(currentThread.quantum);
            }
            
            currentThread.quantum = null;
        }
    };
    
    this.killAllThreads = function() {
        for (var i = 0; i < this.nextThreadId; i++) {
            this.killThread(i);
        }
    };
    
    this.runThread = function(pid) {
        var currentThread = this.threadPool[pid];
        if (currentThread == null) {
            return;
        }
        
        if (currentThread.state == ThreadState.DONE) {
            return;
        }
        
        currentThread.state = ThreadState.RUNNING;
        
        var scheduler = this;

        currentThread.quantum = setTimeout(function() {
            scheduler.runThread(pid);
        }, currentThread.frequency);
        
        if (currentThread.thread != null) {
            currentThread.thread();
        }
    };
};

var Thread = function(callback, frequency) {
    this.thread = callback;
    this.state = ThreadState.READY;
    this.pid = 0;
    this.frequency = frequency ? frequency : 1000/30;
    this.timesRan = 0;
    this.quantum = null;
    
    this.setThread = function(callback) {
        this.thread = function() {
            callback();
        }
    };
};


